﻿using System;
using System.Linq;
using System.Data.Entity;
using GBlog.Core.Data.Default;
using System.Collections.Generic;

namespace GBlog.Core.Data
{
    public class GInitializer : IDatabaseInitializer<GContext>
    {
        /// <summary>
        /// Debug moddayken veritabanını silip baştan oluşturur.
        /// </summary>
        /// <param name="context"></param>
        public void InitializeDatabase(GContext context)
        {
#if DEBUG
            bool flag = context.Database.Exists();
            if (!flag)
            {
                Create(context);
            }
            else
            {

                System.Data.SqlClient.SqlConnection.ClearAllPools();
                context.Database.Delete();
                Create(context);
            }
#endif
        }

        private void Create(GContext context)
        {
            context.Database.Create();
            Seed(context);
            context.SaveChanges();
        }

        /// <summary>
        /// Bütün (dinamik assembly dahil) modeller için başlangıç verilerini girer.
        /// </summary>
        /// <param name="context"></param>
        protected void Seed(GContext context)
        {
            List<Type> types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes()).Where(t => t.IsClass && typeof(IGRegister).IsAssignableFrom(t)).ToList();
            foreach (var type in types)
            {
                IGRegister register = (IGRegister)Activator.CreateInstance(type);
                register.Seed(context);
            }
        }
    }
}